(function($){
    var $current
    var LookupField = function (f) {
        this.$element = $(f);
        this.options={};
        this.init()
    };

    LookupField.DEFAULTS = {
        modalSize :"modal-sm",
        title:"选择",
        currentGroup:"",
        suffix:"",
        $target:null,
        pk:"id"
    };

    LookupField.prototype.init = function () {
        var   that = this;

        this.$element.unbind('click').click(function(event){
            var options = that.$element.attr('data-options')
            if (options && typeof options === 'string') options = options.toObj();
            options = $.extend({}, LookupField.DEFAULTS, options);
            options = $.extend(options, {
                currentGroup: that.$element.attr("lookupGroup") || "",
                suffix: that.$element.attr("suffix") || "",
                pk: that.$element.attr("lookupPk") || "id",
                url:Bolt.smartParseURL(that.$element.attr("href"))
            });
            that.options = options
            $(this).dialog(options);
            $current = that.$element;
            return false;
        });
    }

    LookupField.prototype.getFieldGroup = function(){
        var fieldGroup = [], options = this.options;
        var groups = options.currentGroup.split(",") ;
        $.each(groups,function (index,value) {
            var field ={}
            if(value.indexOf(":") > 0){
                var  fields = value.split(":");
                field[fields[0]] = fields[1];
                fieldGroup.push(field);
            }else{
                field[value] = value;
                fieldGroup.push({value:value});
            }
        })
        return fieldGroup;
    }

    LookupField.prototype.bringBackSuggest = function(args){
        var $box = this.$element.parents(".modal:first") , fieldGroup = this.getFieldGroup();
        if($box.length == 0 ){
            var $box = this.$element.parents(".page-container")
        }
        $.each(fieldGroup,function(index,field){
            for (var key in field) {
                var inputId = key;
                if(key.indexOf(".")>0){
                    inputId = inputId.replace(".","_")
                }
                var  $input = $box.find(':input[id="'+inputId+'"]'), value = field[key];
                if ($input) {
                    $input.val(args[value]);
                    $input.triggerHandler('change');
                }
            }
        });
    }



    function Plugin(option) {
        var args  = args = Array.prototype.slice.call(arguments, 1),
            property = option;
        return this.each(function () {
            var $this   = $(this),options=$this.data().options,
                data = $this.data("bolt.lookupField");
            if (!data) {
                $this.data("bolt.lookupField", (data = new LookupField(this, options)))
            }
            if (typeof property == "string") {
                data[property].apply(data, args);
            }
        })
    }

    $.fn.lookupField = Plugin
    $.fn.lookupField.Constructor = LookupField;
    $.fn.lookupField.defaults = LookupField.DEFAULTS;
    Bolt.bringBack = function(args){
        $current.lookupField('bringBackSuggest',args);
        Bolt.dialog('closeCurrent');
    }

    $(document).on(Bolt.eventType.initUI, function(e) {
        $(e.target).find("a[data-toggle='lookup']").each(function() {
            var $this = $(this),options={}, optionsData = $this.data()
            if (!$this.length) return
            if (optionsData.options && typeof optionsData.options === 'string') optionsData.options = optionsData.options.toObj()
            $.extend(options, typeof optionsData.options === 'object' && optionsData.options)
            Plugin.call($this, options)
        })
    })

    Bolt.addComponent({
        name: "lookupField",
        plugin: Plugin,
        runPoint: Bolt.eventType.afterAjaxPageShow,
        expr: "a[data-toggle='lookup']"
    })
})(jQuery);

